/*
 * Een klasse die de puzzel breadth-first gaat oplossen.
 */

package schuifpuzzelen;

import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Laurens van Dijk, s3012557
 */
public class BFSolver {
    private Puzzle initPuzzel;
    private List<Puzzle> queue, seen;
    private int num_iterations = 0;

    public BFSolver(Puzzle _p) {
        initPuzzel = _p;
        queue = new LinkedList<Puzzle>();
        seen = new LinkedList<Puzzle>();
        queue.add(initPuzzel);
    }

    public Puzzle solve() {
        while (!queue.isEmpty()) {
            Puzzle current = queue.remove(0);
            if (current.isGoal()) {
                return current;
            } else {
                List<Puzzle> possibleSuccessors = new LinkedList<Puzzle>();
                //System.out.println("DBG: current.successors().size() = "+current.successors().size());
                possibleSuccessors.addAll(current.successors());
                for (int i=0; i<possibleSuccessors.size(); i++) {
                    if (seen.contains(possibleSuccessors.get(i))) {
                        System.out.println("DBG: Already seen this one!");
                        possibleSuccessors.remove(i);
                    }
                }
                //System.out.println("DBG: possibleSuccessors.size() = "+possibleSuccessors.size());
                queue.addAll(possibleSuccessors);
                seen.add(current);
            }
            num_iterations++;
            System.out.println(num_iterations);
        }
        return initPuzzel;
    }

    public int getIterations() {
        return num_iterations;
    }
}
